from rest_framework import serializers
from .models import MatchmakingQueue
from apps.decks.serializers import DeckSerializer


class MatchmakingQueueSerializer(serializers.ModelSerializer):
    """匹配队列序列化器"""
    deck = DeckSerializer(read_only=True)
    wait_time = serializers.ReadOnlyField()
    matchmaking_rating = serializers.ReadOnlyField()
    
    class Meta:
        model = MatchmakingQueue
        fields = ('id', 'deck', 'joined_at', 'is_active', 'wait_time', 'matchmaking_rating', 'max_wait_time', 'search_range')
        read_only_fields = ('id', 'joined_at', 'wait_time', 'matchmaking_rating')


class JoinMatchmakingSerializer(serializers.Serializer):
    """加入匹配序列化器"""
    deck_id = serializers.IntegerField()
    
    def validate_deck_id(self, value):
        from apps.decks.models import Deck
        try:
            deck = Deck.objects.get(id=value, user=self.context['request'].user, is_active=True)
        except Deck.DoesNotExist:
            raise serializers.ValidationError("卡组不存在")
        
        # 检查卡组是否完整
        if deck.total_cards != 5:
            raise serializers.ValidationError("卡组必须包含5张卡牌")
        
        return value
